package com.feiyi.app.view;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.feiyi.app.R;
import com.feiyi.app.adapter.ImagePagerAdapter;
import com.feiyi.app.adapter.InfinitePagerAdapter;
import com.feiyi.app.bean.HomePageBean;

import com.feiyi.app.utils.ImageUtil;

import java.util.ArrayList;
import java.util.List;

public class HeadlinesView extends FrameLayout {

    private Handler mHandler;

    //自动滑动的间隔时间
    private int autoScrollDelay = 4000;

    //是否自动滑动
    private boolean isAutoScroll = true;

    //是否正在自动滑动
    private boolean isScrolling = false;

    private InfiniteViewPager mViewPager;

    private PagerAdapter wrappedAdapter;

    private TextView titleTv;

//    private TextView numberTv;
    //点的布局
    private LinearLayout ll_point;

    private AutoScrollViewPager mIndexTextViewPager;

    private LinearLayout mLinearLayout;

    private List<HomePageBean.DataBean.AdsBean> list;

    private LayoutInflater inflater;

    private List<View> viewList;

//    private IndexTextShowPagerAdapter textAdapter;

    private Context mContext;

    public HeadlinesView(Context context) {
        super(context);
        init(context);
    }

    public HeadlinesView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public HeadlinesView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    // 初始化数据
    public void initData(List<HomePageBean.DataBean.AdsBean> feedList) {
        if (null == feedList || feedList.isEmpty()) return;
        this.list = feedList;
        wrappedAdapter = new InfinitePagerAdapter(new ImagePagerAdapter(getContext(), feedList));
        mViewPager.setAdapter(wrappedAdapter);
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        titleTv.setText(list.get(0 % list.size()).getAd_name());
        initPoints(feedList);
        ll_point.getChildAt(0).setEnabled(true);
        this.setVisibility(VISIBLE);
        mHandler = new Handler();
        startAutoScroll();
    }

    // 启动自动滑动 used after initData()
    public void startAutoScroll() {
        if (null != mHandler && !isScrolling) {
            isScrolling = true;
            mHandler.postDelayed(autoScrollTask, autoScrollDelay);
        }
    }

    // 关闭自动滑动 used in onPause()
    public void stopAutoScroll() {
        if (null != mHandler) {
            isScrolling = false;
            mHandler.removeCallbacks(autoScrollTask);
        }
    }

    // 设置是否自动滑动
    public void setAutoScroll(boolean isAutoScroll) {
        this.isAutoScroll = isAutoScroll;
    }

    // 设置自动滑动的间隔时间
    public void setAutoScrollDelay(int autoScrollDelay) {
        this.autoScrollDelay = autoScrollDelay;
    }

    private void init(Context context) {
        this.mContext = context;
        inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.headlines_view, this);
        viewList = new ArrayList<>();
        findViews();
        this.setVisibility(GONE);
    }

    private void findViews() {
        mViewPager = (InfiniteViewPager) findViewById(R.id.headlines_view_vp);
        ImageUtil.suitDisplay1(mViewPager,16,9);
        titleTv = (TextView) findViewById(R.id.headlines_view_title_tv);
        ll_point = (LinearLayout) findViewById(R.id.ll_point_group);
        mLinearLayout = (LinearLayout) findViewById(R.id.linear_index_text_show_hide);
		mIndexTextViewPager = (AutoScrollViewPager) findViewById(R.id.preview_text_index_show);
        startAutoScroll();
    }
    private void initPoints(List<HomePageBean.DataBean.AdsBean> list){
		View v;
		LinearLayout.LayoutParams params;
		for (int i = 0; i < list.size(); i++) {
			// 每循环一次向LinearLayout中添加一个View（点）
			v = new View(mContext);
			v.setBackgroundResource(R.drawable.point_bg);
			v.setEnabled(false); // 设置为未选中状态
			params = new LinearLayout.LayoutParams(18, 18);
			if(i != 0) {
				params.leftMargin = 15;
//				params.setMargins(15, 0, 0, 0);
			}
			v.setLayoutParams(params);
			ll_point.addView(v);
			}
    }

    private Runnable autoScrollTask = new Runnable() {
        @Override
        public void run() {
            if (isAutoScroll && null != mViewPager) {
                int currentItem = mViewPager.getSuperCurrentItem();
                currentItem++;
                if (Integer.MAX_VALUE == currentItem) currentItem = 0;
                mViewPager.setSuperCurrentItem(currentItem);
                //TODO 点的选中状态更改
//                for (int i = 0; i <ll_point.getChildCount(); i++) {
//    				if (i == currentItem) {
    					ll_point.getChildAt(currentItem%list.size()).setEnabled(true);
//    				}else{
//    					ll_point.getChildAt(i).setEnabled(false);
//    				}
//    			}
                
                isScrolling = false;

                startAutoScroll();
            }
        }
    };

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                stopAutoScroll();
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                startAutoScroll();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            titleTv.setText(list.get(position % list.size()).getAd_name());
         // 获取真实的索引
//    		int realPosition = position % list.size();
//            numberTv.setText(new StringBuilder().append((position) % list.size() + 1).append("/")
//                    .append(list.size()));
            //TODO 改变小点的选中状态
            for (int i = 0; i <list.size(); i++) {
				if (i == position%list.size()) {
					ll_point.getChildAt(i).setEnabled(true);
				}else{
					ll_point.getChildAt(i).setEnabled(false);
				}
			}
            
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

}
